<html>
<div id="loading">
<img src=images/loading.gif> <font color=#008080 size=3><b> Please wait a second ...</b></font>
</div>
<script>
function hideLoading()
{
  var disp = document.getElementById('loading');
  disp.innerHTML = '';
}

</script>

<body>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';
include 'head.htm';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$_SESSION['tab'] = 0;
$act = getHttpVal('act', 'New');
$start = getHttpVal('start', 0);
$id=getHttpVal('id',-1);
//echo 'act='.$act.', id='.getHttpVal('id',-1).', counter='.getHttpVal('counter',-1);
//Creates a blank array.
$ldapUsers = array();

if (strcmp($act,'GetUsers')==0 && $id > 0) {
  $client = $_SESSION['client'];  
  // pName pHost pPort pProtocol pBaseDN pUserDN pPassword pSchedule pTimeout pFilter pNotes
  writeLog("LDAPUserImport::Main Update call", true);
  $pName = getHttpVal('pName', '');
  $pHost = getHttpVal('pHost', '');
  $pPort = getHttpVal('pPort', 389);
  $pProtocol = 3;
  $pBaseDN = getHttpVal('pBaseDN', '');
  $pUserDN = getHttpVal('pUserDN', '');
  $pPassword = getHttpVal('pPassword', '');
  $pFilter = getHttpVal('pFilter', '');
  $pLoginNameID = getHttpVal('pLoginNameID', ''); 
  
  /// Connect to the LDAP server using above constrains
  echo '<font color=#008080 size=2> Connecting to server '.$pHost.' ... ';
  $ds=ldap_connect($pHost);  // must be a valid LDAP server!
  
  if ($ds) { 

	if (ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,$pProtocol))
	{
		echo 'Using LDAP v3 <br><br>';
	}else{
		echo 'Failed to set version to protocol 3 <br><br>';
	}
    $r=ldap_bind($ds, $pUserDN, $pPassword);     // read-only access
    
    //$sr=ldap_search($ds, $pBaseDN, $pFilter);
    if($r) {
      $justthese = array("cn", "department", strtolower($pLoginNameID));
    
      $sr=ldap_list($ds, $pBaseDN, $pFilter, $justthese);  
    
      $info = ldap_get_entries($ds, $sr);
      //echo 'Data for '.$info["count"].' items returned:<p>';
  
      ///  Get the login names list using LoginNameID  

      for ($i=0; $i<$info["count"]; $i++) {
        //echo 'first cn entry is: '.$info[$i]['cn'][0].'<br />';
        //echo 'first department entry is: '.$info[$i]['department'][0].'<br />';
        //echo 'first sAMAccountName entry is: '.$info[$i]['samaccountname'][0].'<br /><hr />';
		/// Update the array list of login names 
		$ldapUsers[] = $info[$i][strtolower($pLoginNameID)][0];
      }

      echo 'Closing connection <br>';
      ldap_close($ds);
    
      // Importing ------ $tableName
      if (count($ldapUsers) > 0) {
        $tmpTableName = 'TMP_'.$client;
        createTempTable($tmpTableName);
        user_bulk_insert($ldapUsers, $tmpTableName);
        $n = addNewUsersFromLDAP($tmpTableName, $client);
        echo '<b> '.$n.' new users added for the client '.$client.' </b><br>';
        $n = diableUsersDeletedFromLDAP($tmpTableName, $client);
        echo '<b> '.$n.' users de-activated for the client '.$client.' </b><br>';
      } else {
      	echo '<br>No user records found in configured server <br><br>';
      }
    } else {
      echo '<br>Failed to authenticate the user please check the credentials <br><br>';
    }
    echo '<br><br><br><b><a href=user_import_policy.php>&gt;&gt; Back to the User Import</a></b></font><br><br>';
   

  } else {
    echo '<h4>Unable to connect to LDAP server</h4>';
    echo '<br><br><br><b><a href=user_import_policy.php>&gt;&gt; Back to the User Import</a></b></font><br><br>';
  }    
  /// display the list 
  
} else {
  /// Add the new users to the DB
  writeLog("LDAPUserImport::Main selecting call call", true);  
}

function user_bulk_insert($users, $temptable) {

  $stmt = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
  // make those values safe
  $users = addslashes_recursive($users);
  // join and quote the whole lot
  $stmt = $stmt . "('" . implode("'),('", $users) . "')";
  writeLog("LDAPUserImport::user_bulk_insert QRY :: ".$stmt, true);
  $tlog = "\t+ " . count($users) . " users\n";
  writeLog("LDAPUserImport::user_bulk_insert User count :: ".$tlog, true);
    
  if ($r = query($stmt)) {
  	writeLog("LDAPUserImport::user_bulk_insert Insert Done ".$temptable, true);
  	return 1;
  }  else {
  	writeLog("LDAPUserImport::user_bulk_insert Error in Insert ".$temptable, true);
  	return 0;	
  }
}

function addslashes_recursive($var) {
    if (is_object($var)) {
        $new_var = new object();
        $properties = get_object_vars($var);
        foreach($properties as $property => $value) {
            $new_var->$property = addslashes_recursive($value);
        }

    } else if (is_array($var)) {
        $new_var = array();
        foreach($var as $property => $value) {
            $new_var[$property] = addslashes_recursive($value);
        }

    } else if (is_string($var)) {
        $new_var = addslashes($var);

    } else { // nulls, integers, etc.
        $new_var = $var;
    }

    return $new_var;
}

function createTempTable($tableName) {

  $stmt = 'DROP TEMPORARY TABLE IF EXISTS '.$tableName;
  //$stmt = 'DROP TABLE IF EXISTS '.$tableName; 
  $r = query($stmt);
  
  $stmt = 'CREATE TEMPORARY TABLE '.$tableName.' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
  //$stmt = 'CREATE TABLE '.$tableName.' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
  if ($r = query($stmt)) {
  	writeLog("LDAPUserImport::createTempTable Tmp tbl created ".$tableName, true);
  	return 1;
  }  else {
  	writeLog("LDAPUserImport::createTempTable Error while creating Tmp tbl ".$tableName, true);
  	return 0;	
  }
}

function addNewUsersFromLDAP($temptable, $client) {
  $dt2=date("Y-m-d H:i:s");
	//SELECT e.username, e.username
    //    FROM TMP_1678 e LEFT JOIN users u ON e.username = u.login_name
    //    WHERE u.user_id IS NULL
  $grpID = getGroupId($client.'_ldap_users');
  $stmt = 'SELECT e.username FROM '.$temptable.' e LEFT JOIN users u ON (u.client_id = '.$client.') AND e.username = u.login_name WHERE u.user_id IS NULL';
  $redStmt = 'INSERT INTO users(client_id, user_status, group_id, user_name, user_type, login_name, notes, created, accessed) VALUES';

  $r = query($stmt);
  $n=mysql_num_rows($r);
  writeLog("ListUsers::addNewUsersFromLDAP New user Count = ".$n , true);  	
  $i = 0;
  while ($row=mysql_fetch_assoc($r)) {
  	// insert stmt for new users   $row['user_status']
  	//(1678, 1, 5, 'Ni', 'admin', 'npatil', '', '2009-01-23 00:59:26', '2009-01-23 00:59:26')
  	$redStmt .= ' ('.$client.',1,'.$grpID.','.mysql_quote($row['username']).', "user", '.mysql_quote($row['username']).
    ', "Fetched from LDAP/AD", '.mysql_quote($dt2).', '.mysql_quote($dt2).')';
    $i++;
    
    if ($i != $n) {
    	$redStmt .= ',';
    }
  }
  mysql_free_result($r);
  
  /// Insert new users 
  writeLog("ListUsers::addNewUsersFromLDAP New user Stmt :: > ".$redStmt, true);
  if ($n > 0) {
    if ($r = query($redStmt)) {
  	  return $n;
    } else {
  	  return 0;	
    }
  }
  return $n;
}

function diableUsersDeletedFromLDAP($temptable, $client) {
  $dt2=date("Y-m-d H:i:s");
	//SELECT u.user_id, u.login_name  FROM users u
	//LEFT JOIN TMP_1678 e ON u.login_name = e.username
    //    WHERE e.username IS NULL
  $stmt = 'SELECT u.user_id, u.login_name FROM users u LEFT JOIN '.$temptable.' e ON u.login_name = e.username WHERE ((u.client_id = '.$client.') AND (user_status=1) ) AND (e.username IS NULL)';
  $redStmt = 'UPDATE users SET notes="Inactive as deleted from LDAP ", user_status=0, accessed='.mysql_quote($dt2).' WHERE (client_id = '.$client.') AND (login_name in ('; // <list>))

  $r = query($stmt);
  $n=mysql_num_rows($r);
  writeLog("ListUsers::diableUsersDeletedFromLDAP New user Count = ".$n , true);  	
  
  while ($row=mysql_fetch_assoc($r)) {
  	// insert stmt for new users   $row['user_status']
  	//(1678, 1, 5, 'Ni', 'admin', 'npatil', '', '2009-01-23 00:59:26', '2009-01-23 00:59:26')
  	$redStmt .= ' '.mysql_quote($row['login_name']).',';
  }
  $redStmt .= ' " "))';
  mysql_free_result($r);
  
  /// Insert new users 
  writeLog("ListUsers::diableUsersDeletedFromLDAP Disable user Stmt :: > ".$redStmt, true);
  
  if ($n > 0) {
    if ($r = query($redStmt)) {
   	  return $n;
    }  else {
  	  return 0;	
    }
  }
  return $n;
}
?>

<script>
hideLoading();
</script>
</body>
</html>
